package com.imy.alscript;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import java.util.List;

/**
 * @ProjectName: YuanShenMap
 * @Package: com.imy.yuanshenmap
 * @ClassName: CommenUtils
 * @Description: 描述
 * @Author: 蒋明伟
 * @CreateDate: 2020/11/4 14:18
 */
public class CommonUtils {

    /**
     * 判断手机是否安装某个应用
     *
     * @param context
     * @param appPackageName 应用包名
     * @return true：安装，false：未安装
     */
    public static boolean isApplicationAvilible(Context context, String appPackageName) {

        if (null == context || null == appPackageName) {
            return false;
        }

        boolean bHas = true;
        try {
            context.getPackageManager().getPackageInfo(appPackageName, PackageManager.GET_GIDS);
        } catch (PackageManager.NameNotFoundException e) {
            // 抛出找不到的异常，说明该程序已经被卸载
            bHas = false;
        }
        return bHas;
//    PackageManager packageManager = context.getPackageManager();// 获取packagemanager
//    List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
//    if (pinfo != null) {
//      for (int i = 0; i < pinfo.size(); i++) {
//        String pn = pinfo.get(i).packageName;
//        if (appPackageName.equals(pn)) {
//          return true;
//        }
//      }
//    }
//    return false;
//        PackageManager pm = context.getPackageManager();
//        // 查询所有已经安装的应用程序
//        List<ApplicationInfo> appInfos = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);// GET_UNINSTALLED_PACKAGES代表已删除，但还有安装目录的
//        List<ApplicationInfo> applicationInfos = new ArrayList<>();
//
//        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
//        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
//        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//
//        // 通过getPackageManager()的queryIntentActivities方法遍历,得到所有能打开的app的packageName
//        List<ResolveInfo> resolveinfoList = pm
//                .queryIntentActivities(resolveIntent, 0);
//        for (ResolveInfo resolveInfo : resolveinfoList) {
//            String packageName = resolveInfo.activityInfo.packageName;
//            if (packageName.equals(appPackageName)) {
//                return true;
//            }
//        }
//        return false;
    }

    /**
     * 中文转化
     */
    private static String encodeHeadInfo(String headInfo) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0, length = headInfo.length(); i < length; i++) {
            char c = headInfo.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                stringBuffer.append(String.format("\\u%04x", (int) c));
            } else {
                stringBuffer.append(c);
            }
        }
        return stringBuffer.toString();
    }


    /**
     * 判断服务是否在运行
     *
     * @param context
     * @param serviceName
     * @return 服务名称为全路径 例如com.ghost.WidgetUpdateService
     */
    public static boolean isRunService(Context context, String serviceName) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceName.equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    public static boolean isApkInDebug(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isAppRunning(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;
        //String MY_PKG_NAME = "你的包名";
        for (ActivityManager.RunningTaskInfo info : list) {
            Log.i("common", info.topActivity.getPackageName()
                    + " info.baseActivity.getPackageName()="
                    + info.baseActivity.getPackageName());
            if (info.topActivity.getPackageName().equals(packageName)//如果想要手动输入的话可以str换成<span style="font-family: Arial, Helvetica, sans-serif;">MY_PKG_NAME，下面相同</span>
                    || info.baseActivity.getPackageName().equals(packageName)) {
                isAppRunning = true;
                break;
            }
        }
        return isAppRunning;

    }

    /**
     * 启动第三方apk
     * <p>
     * 如果已经启动apk，则直接将apk从后台调到前台运行（类似home键之后再点击apk图标启动），如果未启动apk，则重新启动
     */
    public static void launchYuanShen(Context context) {
        Intent intent = getAppOpenIntentByPackageName(context, "com.miHoYo.Yuanshen");
        if (intent == null) {
            //测试id
            Intent intent1;
            if (isApkInDebug(context)) {
                intent1 = new Intent(Intent.ACTION_VIEW, Uri.parse("imy://openTopic?type=gamedetail&gameId=116867"));
            } else {
                intent1 = new Intent(Intent.ACTION_VIEW, Uri.parse("imy://openTopic?type=gamedetail&gameId=106235"));
            }
            //正式id
            context.startActivity(intent1);
        } else {
            context.startActivity(intent);
        }

    }

    /**
     * 跳转到通知权限设置界面
     */
    public static void openNotificationSetting(Context context) {
        Intent intent = new Intent();
        try {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                intent.putExtra("app_package", context.getPackageName());
                intent.putExtra("app_uid", context.getApplicationInfo().uid);
            } else {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.fromParts("package", context.getPackageName(), null));
            }
        } catch (Exception e) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        }
        // 判断是否含有intent的目标activity，有的话再跳转
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    /**
     * 启动第三方apk
     * <p>
     * 如果已经启动apk，则直接将apk从后台调到前台运行（类似home键之后再点击apk图标启动），如果未启动apk，则重新启动
     */
    public static void launchSelf(Context context) {
        Intent intent = getAppOpenIntentByPackageName(context, "com.imy.yuanshenmap");
        if (intent!=null){

        }
        context.startActivity(intent);
    }

    public static Intent getAppOpenIntentByPackageName(Context context, String packageName) {
        String mainAct = null;
        PackageManager pkgMag = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);

        @SuppressLint("WrongConstant") List<ResolveInfo> list = pkgMag.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        for (int i = 0; i < list.size(); i++) {
            ResolveInfo info = list.get(i);
            if (info.activityInfo.packageName.equals(packageName)) {
                mainAct = info.activityInfo.name;
                break;
            }
        }
        if (TextUtils.isEmpty(mainAct)) {
            return null;
        }
        intent.setComponent(new ComponentName(packageName, mainAct));
        return intent;
    }
}